<template>
	<view :class="[primarySize()]">
		<view class="container bg-white">
			<view class="bg-white ptb15">
				<view class="search_nav flex-box m-shadow">
					<input type="text" confirm-type="search" @confirm="search" v-model="keyword" @input="search"
						placeholder="请输入关键词进行搜索" class="inp_nav flex-grow-1" placeholder-class="colnor" />
					<image src="https://admin.mosizp.cn/static/public/icon_search.png" mode="aspectFill" class="ico28" @click="search">
					</image>
				</view>
			</view>
			<view class="popup" v-if="keyword ">
				<template v-if="searchResult.length > 0">
					<template v-for="item in searchResult">
						<view :id="item.id">
							<view class="plr30">
								<view class="city" v-for="city in item" @click="bindCityChange(city)">{{city.name}}
								</view>
							</view>
						</view>
					</template>
				</template>
				<template v-if="searchResult.length==0 && result">
					<view class="plr30">
						<view class="city">没有找到匹配的城市</view>
					</view>
				</template>
			</view>
			<scroll-view scroll-y="true" v-else>
				<template v-for="item in cities">
					<view :id="item.id">
						<view class="letter">{{item.first}}</view>
						<view class="plr30">
							<view class="city" v-for="city in item.cities" @click="bindCityChange(city)">{{city.name}}
							</view>
						</view>
					</view>
				</template>

			</scroll-view>
		</view>
	</view>
</template>
<script>
	const app = getApp();
	export default {
		data() {
			return {
				scrollTop: 0,
				cities: [],
				keyword: '',
				searchResult: [],
				result: false
			};
		},
		onReady() {
			uni.setNavigationBarColor({
				frontColor: '#ffffff',
				backgroundColor: this.primaryColor()
			})
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad(options) {
			this.$util.getAllCities(false).then(areas => {
				this.cities = areas;
			});
		},
		mounted() {
			this.searchResult = [...this.cities];
		},
		onPageScroll(e) {
			this.scrollTop = e.scrollTop;
		},
		methods: {
			/**
			 * 在二维数组中模糊搜索
			 * @param {Array<Array>} twoDArray 要搜索的二维数组
			 * @param {string} searchTerm 搜索词
			 * @param {boolean} [searchInSubArrays=true] 是否在子数组中搜索
			 * @return {Array} 匹配的元素数组
			 */
			fuzzySearchIn2DArray(twoDArray, searchTerm, searchInSubArrays = true) {
				if (!searchTerm) return []; // 如果搜索词为空，返回原数组

				const results = [];
				const lowerSearchTerm = searchTerm.toLowerCase();

				for (const item of twoDArray) {
					if (Array.isArray(item.cities)) {
						if (searchInSubArrays) {
							// 如果是子数组且需要搜索子数组，则递归处理

							const subResults = this.fuzzySearchIn2DArray(item.cities, searchTerm, true);
							if (subResults.length > 0) {
								results.push(subResults);
							}
						}
					} else {
						// 对非数组元素进行模糊匹配
						if (String(item.name).toLowerCase().includes(lowerSearchTerm)) {
							results.push(item);
						}
					}
				}
				return results;
			},
			bindCityChange(city) {
				this.$core.setCurrentCity(city);
				uni.navigateBack({})
			},
			search() {
				clearTimeout(this.timer);
				this.searchResult = [];
				this.result = false;
				this.timer = setTimeout(() => this.fuzzySearch(), 300);
			},
			fuzzySearch() {
				const rawKeyword = this.keyword.trim();
				if (!rawKeyword) {
					this.searchResult = [...this.cities];
					return;
				}

				// 安全处理正则特殊字符
				const safeKeyword = rawKeyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

				// 拆分多关键词（支持AND逻辑）
				const keywords = safeKeyword.toLowerCase();

				try {
					this.searchResult = this.fuzzySearchIn2DArray(this.cities, keywords)
					this.result = true
					this.$forceUpdate()
				} catch (err) {
					console.error('正则表达式错误:', err);
					this.searchResult = [];
				}
			},
		}
	};
</script>
<style lang="less" scoped>
	.search_nav {
		width: 690rpx;
		height: 75rpx;
		background: #FFFFFF;
		border-radius: 50rpx;
		margin-left: auto;
		margin-right: auto;
		padding: 0 30rpx;
		margin-bottom: 1px;

		.inp_nav {
			position: relative;
			padding-right: 30rpx;
			font-size: 28rpx;
			color: #101010;
			position: relative;
		}

	}

	scroll-view {
		height: calc(100vh - 115rpx);


	}

	.letter {
		padding: 0 40rpx;
		height: 50rpx;
		background: #f6f7fa;
		font-size: 26rpx;
		color: #898989;
		line-height: 50rpx;
	}

	.city {
		height: 105rpx;
		font-size: 34rpx;
		color: #101010;
		line-height: 105rpx;
	}

	.city+.city {
		border-top: 1rpx solid #eeeeee;
	}

	.popup {
		position: fixed;
		width: 100%;
		height: calc(100vh - 115rpx);
		top: 115rpx;
		left: 0;
		right: 0;
		z-index: 20;
		background: #FFFFFF;
	}
</style>